package com.cjc.sport.controller;

//import com.cjc.sport.entity.EnumValidation;

import com.cjc.sport.entity.EnumValidation;
import com.cjc.sport.exception.ServiceException;
//import org.springframework.util.ClassUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;
//import org.springframework.web.bind.annotation.*;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.util.UUID;

/**
 * 测试上传图片
 */
@RestController
@CrossOrigin
@Slf4j
public class PageController {
    /**
     * 获取配置文件
     */
    private Environment environment;

    /**
     * 上传连接
     *
     * @param request 请求对象
     * @param file    文件名
     * @return 图片地址
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String upload(HttpServletRequest request, MultipartFile file) {
        String fileNameTemp = "";

        try {
//            // 获取文件内容大小
//            long size = file.getSize();
//            if (size == 0) {
//                // 判断文件内容是否为空
//                throw new ServiceException("文件内容为空");
//            }
//            String uploadDir = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "picture/";
//            System.out.println(uploadDir);
//
//            File dir = new File(uploadDir);
//            if (!dir.exists()) {
//                dir.mkdir();
//            }
//            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
//            System.out.println(suffix);
//            if (!(suffix.equals(".jpg") || suffix.equals(".png") || suffix.equals(".gif"))) {
//                throw new ServiceException("图片格式为png或gif或png!");
//            }
////            String filename = file.getOriginalFilename();
//            String filename = UUID.randomUUID() + suffix;
//            File serverFile = new File(uploadDir + filename);
//            file.transferTo(serverFile);
//            String completePath = uploadDir + filename;
//            if (completePath.substring(EnumValidation.TWO.getNum(), EnumValidation.THREE.getNum()).equals(":")) {
//                completePath = completePath.substring(1, completePath.length());
//            }
//            return completePath;

            String uploadDir = request.getSession().getServletContext().getRealPath("/") + "upload/";
            System.out.println(uploadDir);

//            String uploadDir = this.getClass().getClassLoader().getResource("").getPath();
//            System.out.println(uploadDir);
//            uploadDir = uploadDir.replace("/WEB-INF/classes/", "") + "/upload/";
//            System.out.println(uploadDir);


//            File directory = new File("");
//            String uploadDir = directory.getCanonicalPath();
//            uploadDir = uploadDir + "/upload/";
//            System.out.println(uploadDir);
            // 获取文件内容大小
            long size = file.getSize();
            if (size == 0) {
                // 判断文件内容是否为空
                throw new ServiceException("上传图片为空!");
            }
            if (size > EnumValidation.FIVE.getNum() * EnumValidation.MB.getNum()) {
                throw new ServiceException("请上传图片大小为5MB以下的图片!");
            }

//            String uploadDir = request.getSession().getServletContext().getRealPath("/") + "upload/";
//            System.out.println(uploadDir);
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdir();
            }
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            if (".gif".equals(suffix)) {
                throw new ServiceException("图片格式不能为为gif!");
            }

            String filename = UUID.randomUUID() + suffix;
            File serverFile = new File(uploadDir + filename);
            file.transferTo(serverFile);
            fileNameTemp = uploadDir + filename;

            BufferedImage sourceImg = ImageIO.read(new FileInputStream(fileNameTemp));
            int imgWidth = sourceImg.getWidth();
            int imgHeight = sourceImg.getHeight();
            System.out.println("图片高度：" + imgHeight + " 图片宽度: " + imgWidth);

            return "/upload/" + filename;

        } catch (ServiceException s) {
            return s.getMessage();
        } catch (NullPointerException n) {
            File tempFile = new File(fileNameTemp);
            System.out.println(fileNameTemp);
            tempFile.delete();
            return "上传失败，请检查图片是否为能正常打开的图片！";
        } catch (Exception e) {
            e.printStackTrace();
            return "上传失败";
        }
    }

    /**
     * 测试
     * @return 测试
     */
    @RequestMapping(value = "test1")
    public String test() {
        return "12ds";
    }
}
